{% extends 'base.html' %}
{% block title %}Namespaces{% endblock %}
{% block nav-item-1 %}layui-nav-itemed{% endblock %}
{% block nav-this-1-2 %}layui-this{% endblock %}
{% block content %}
    <span class="layui-breadcrumb">
      <a href="#">首页</a>
      <a href="#">Kubernetes</a>
      <a><cite>Namespaces</cite></a>
    </span>
    <hr>

    <div  id="modal"  style="display: none">
        <form class="layui-form " action="">
          <div class="layui-form-item" style="padding: 10px 100px 10px 10px">
            <label class="layui-form-label">名称：</label>
            <div class="layui-input-block">
              <input type="text" name="name" lay-verify="required" lay-reqtext="名称是必填项!" autocomplete="off" class="layui-input">
                <br><br>
              <button type="button" class="layui-btn" lay-submit="" lay-filter="btn" style="margin-left: 25%">立即提交</button>
            </div>
          </div>
        </form>
    </div>

    <div class="layui-card">
        <div class="layui-card-body">

            <div class="layui-row">
                <div class="layui-col-md12">
                    <button class="layui-btn" style="float: left" id="createNS">创建</button>
                    <input type="text" name="name" class="layui-input" style="width: 150px;float: left;margin-left: 20px">
                    <button class="layui-btn" style="float: left" id="searchBtn">搜索</button>
                </div>
                <div class="layui-col-md12">
                    <table class="layui-hide" id="test" lay-filter="test"></table>
                    <script type="text/html" id="barDemo">
                      <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="yaml">YAML</a>
                      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                    </script>
                </div>
            </div>

        </div>
    </div>

{% endblock %}

{% block js %}
<script>
layui.use(['table','layer','form'], function(){
  var table = layui.table;
  var form = layui.form;
  var layer = layui.layer;
  var $ = layui.jquery;

  table.render({
    elem: '#test'
    ,url:'{% url 'namespace_api' %}'
    ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
    ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
      title: '提示'
      ,layEvent: 'LAYTABLE_TIPS'
      ,icon: 'layui-icon-tips'
    }]
    ,title: '用户数据表'
    ,cols: [[
      {field:'name', title:'名称', sort: true}
      ,{field:'labels', title:'标签',templet: labelsFormat}
      ,{field:'create_time', title:'创建时间'}
      ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
    ]]
    ,page: true
    ,id: 'nstb'
  });

    function labelsFormat(d) {
        //console.log(d.labels)
        result = "";
        if (d.labels == null) {
            return "None"
        } else {
            for(let key in d.labels){
                result += '<span style="border:1px solid #d6e5ec;border-radius: 8px">' +
                    key + ":" + d.labels[key] + "</span><br>"
            }
            return  result
        }
    }

  //监听行工具事件
  table.on('tool(test)', function(obj){
    var data = obj.data;
    //console.log(obj)
    if(obj.event === 'del'){
      layer.confirm('真的要删除' + data["name"] + "这个命名空间吗？", function(index){
          csrf_token = $('[name="csrfmiddlewaretoken"]').val();
        $.ajax({
            url: '{% url 'namespace_api' %}',
            type: "DELETE",
            data: data,
            headers: {"X-CSRFToken": csrf_token},
            success: function (res) {
                if (res.code == 0) {
                    layer.msg(res.msg, {icon: 6});
                    obj.del()
                } else {
                    layer.msg(res.msg, {icon: 5})
                }
            },
            error: function () {
                layer.msg("服务器接口异常",{icon: 5})
            }
        })

      });
    } else if(obj.event === 'yaml'){
        layer.open({
            title: 'YAML',
            type: 2,
            area: ['50%', '60%'],
            content: "{% url 'ace_editor' %}?resource=namespace&" + 'namespace=' + data['namespace'] + '&name=' + data['name'],
        })
    }
  });
    // 监听搜索按钮事件
    $("#searchBtn").click(function () {
        var search_key = $("input[name='name']").val();
        table.reload('nstb', {
          where: { //设定异步数据接口的额外参数，任意设
            search_key: search_key
          }
          ,page: {
            curr: 1 //重新从第 1 页开始
          }
        }); //只重载数据
    });

    // 绑定创建按钮事件
    $('#createNS').on('click', function () {
        layer.open({
            title: "创建命名空间",
            type: 1,
            content: $('#modal').html(),
            success: function(index, layero) {
                form.on('submit(btn)', function (data) {
                   data = data.field;
                   csrf_token = $('[name="csrfmiddlewaretoken"]').val();
                   data['csrfmiddlewaretoken'] = csrf_token;
                   $.ajax({
                       url: '{% url "namespace_api" %}',
                       type: 'POST',
                       data: data,
                       dataType: 'json',
                       // 提交成功回调函数
                       success: function (res) {
                           if(res.code == '0'){
                               layer.msg(res.msg,{icon:6});
                               window.location.reload();
                           } else {
                               layer.msg(res.msg, {icon:5})
                           }
                       },
                       // 访问接口失败函数
                       error: function (res) {
                           layer.msg("服务器接口异常！", {icon:5})
                       }
                   })
               })

            }
        })
    })

});
</script>

{% endblock %}